const constants = require("../../data/constants");
const log4js = require('../../data/log');
const logger = log4js.getLogger('sip');
const sipUtils = require('../../utils/sipUtils');
/**
 * 生成 invite 响应信令
 */
module.exports={
    generate(rs) {
        let cseq = Object.assign({}, rs.headers.cseq);
        let callId = rs.headers['call-id'];
        let inviteObj = constants.registry.invites[callId];
        let deviceId = inviteObj.deviceid;
        let deviceInfo = constants.registry[deviceId];
        cseq.method = 'ACK';

        let uri = sipUtils.generateUri(deviceId, inviteObj.channel, null, deviceInfo.sip_command_host, deviceInfo.sip_command_port);

        let channelInfo = deviceInfo.channels[inviteObj.channel];
        let ret;
        if (!channelInfo) {
            logger.error(`设备通道信息不存在,deviceId=${deviceId}`);
            ret = null;
        }else {
            if (!channelInfo.invite) {
                channelInfo.invite = {headers: {}};
            }
            channelInfo.invite.headers.to = Object.assign({}, rs.headers.to);
            channelInfo.invite.headers.from = Object.assign({}, rs.headers.from);
            channelInfo.invite.headers['call-id'] = rs.headers['call-id'];
            channelInfo.invite.headers.cseq = rs.headers.cseq;

            ret = {
                method: cseq.method, uri,
                headers: {
                    via: sipUtils.generateVia(channelInfo.protocol),
                    from: rs.headers.from,
                    to: rs.headers.to,
                    'call-id': rs.headers['call-id'],
                    cseq,
                    'Max-Forwards': 70,
                    'User-Agent': constants.sip.useragent
                }
            };
        }
        return ret;
    }
}
